<template>
  <div class="home-container">
    <!-- 博客信息区域 -->
    <n-card class="blog-info-card">
      <div class="blog-info">
        <n-avatar
          :src="blogConfig?.blogAvatar"
          :size="80"
          round
        />
        <div class="blog-details">
          <n-text class="blog-name" strong>
            {{ blogConfig?.blogName || '我的博客' }}
          </n-text>
          <n-text class="blog-desc" depth="3">
            {{ blogConfig?.personalSay || '分享技术，记录生活' }}
          </n-text>
          <n-text v-if="blogConfig?.blogNotice" class="blog-notice" depth="3">
            📢 {{ blogConfig.blogNotice }}
          </n-text>
        </div>
      </div>
    </n-card>

    <!-- 内容区域 -->
    <div class="content-grid">
      <!-- 最近的说说 -->
      <n-card title="最近的说说" class="content-card">
        <template #header-extra>
          <n-button text @click="$router.push('/talk')">
            查看更多 <n-icon><i class="fas fa-arrow-right"></i></n-icon>
          </n-button>
        </template>
        <div v-if="recentTalks.length > 0">
          <div
            v-for="talk in recentTalks"
            :key="talk.id"
            class="talk-item"
          >
            <div class="talk-header">
              <n-avatar :src="talk.avatar || talk.user?.avatarUrl" :size="32" round />
              <div class="talk-info">
                <n-text strong>{{ talk.nickname || talk.user?.nickname }}</n-text>
                <n-text depth="3" size="small">{{ formatTime(talk.createTime) }}</n-text>
              </div>
            </div>
            <n-text class="talk-content">{{ talk.content }}</n-text>
            <div v-if="talk.tags && talk.tags.length > 0" class="talk-tags">
              <n-tag
                v-for="tag in talk.tags"
                :key="tag"
                size="small"
                type="primary"
              >
                {{ tag }}
              </n-tag>
            </div>
          </div>
        </div>
        <n-empty v-else description="暂无说说" />
      </n-card>

      <!-- 最近的文章 -->
      <n-card title="最近的文章" class="content-card">
        <template #header-extra>
          <n-button text @click="$router.push('/article')">
            查看更多 <n-icon><i class="fas fa-arrow-right"></i></n-icon>
          </n-button>
        </template>
        <div v-if="recentArticles.length > 0">
          <div
            v-for="article in recentArticles"
            :key="article.id"
            class="article-item"
          >
            <n-text strong class="article-title">{{ article.title }}</n-text>
            <n-text depth="3" class="article-desc">{{ article.abstract }}</n-text>
            <div class="article-meta">
              <n-text depth="3" size="small">{{ formatTime(article.createTime) }}</n-text>
              <n-text depth="3" size="small">阅读 {{ article.viewCount }}</n-text>
            </div>
          </div>
        </div>
        <n-empty v-else description="暂无文章" />
      </n-card>

      <!-- 最近的相册 -->
      <n-card title="最近的相册" class="content-card">
        <template #header-extra>
          <n-button text @click="$router.push('/album')">
            查看更多 <n-icon><i class="fas fa-arrow-right"></i></n-icon>
          </n-button>
        </template>
        <div v-if="recentAlbums.length > 0">
          <div class="album-grid">
            <div
              v-for="album in recentAlbums"
              :key="album.id"
              class="album-item"
            >
              <n-image
                :src="album.cover"
                :width="120"
                :height="120"
                object-fit="cover"
                preview-disabled
              />
              <n-text class="album-title">{{ album.title }}</n-text>
            </div>
          </div>
        </div>
        <n-empty v-else description="暂无相册" />
      </n-card>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useUserStore } from '@/stores/user'
import { talkApi } from '@/api/talk'
import dayjs from 'dayjs'

const userStore = useUserStore()

// 响应式数据
const recentTalks = ref<any[]>([])
const recentArticles = ref<any[]>([])
const recentAlbums = ref<any[]>([])

// 计算属性
const blogConfig = computed(() => userStore.blogConfig)

// 格式化时间
const formatTime = (time: string) => {
  return dayjs(time).format('YYYY-MM-DD HH:mm')
}

// 获取最近说说
const fetchRecentTalks = async () => {
  try {
    const response = await talkApi.getTalkList({
      pageNum: 1,
      pageSize: 5
    })
    console.log('API响应:', response)
    recentTalks.value = response.list || []
    console.log('获取到的说说:', recentTalks.value)

    // 检查第一个说说的数据结构
    if (recentTalks.value.length > 0) {
      console.log('第一个说说的数据结构:', JSON.stringify(recentTalks.value[0], null, 2))
    }
  } catch (error) {
    console.error('获取最近说说失败:', error)
    // 如果获取失败，显示一些示例数据
    recentTalks.value = [
      {
        id: 1,
        content: '这是一条示例说说，展示说说功能',
        createTime: new Date().toISOString(),
        user: {
          nickname: '示例用户',
          avatarUrl: 'https://via.placeholder.com/32x32'
        },
        tags: ['示例', '测试']
      }
    ]
  }
}

// 获取最近文章（模拟数据）
const fetchRecentArticles = async () => {
  // 这里应该调用文章API
  recentArticles.value = [
    {
      id: 1,
      title: '示例文章标题',
      abstract: '这是一篇示例文章的摘要...',
      createTime: new Date().toISOString(),
      viewCount: 100
    }
  ]
}

// 获取最近相册（模拟数据）
const fetchRecentAlbums = async () => {
  // 这里应该调用相册API
  recentAlbums.value = [
    {
      id: 1,
      title: '示例相册',
      cover: 'https://via.placeholder.com/120x120'
    }
  ]
}

// 生命周期
onMounted(async () => {
  // 获取博客配置
  if (!blogConfig.value) {
    await userStore.fetchBlogConfig()
  }

  // 获取最近内容
  await Promise.all([
    fetchRecentTalks(),
    fetchRecentArticles(),
    fetchRecentAlbums()
  ])
})
</script>

<style scoped>
.home-container {
  max-width: 1200px;
  margin: 0 auto;
}

.blog-info-card {
  margin-bottom: 24px;
}

.blog-info {
  display: flex;
  align-items: center;
  gap: 20px;
}

.blog-details {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.blog-name {
  font-size: 24px;
}

.blog-desc {
  font-size: 16px;
  line-height: 1.5;
}

.blog-notice {
  font-size: 14px;
  padding: 8px 12px;
  background: #f0f9ff;
  border-radius: 6px;
  border-left: 4px solid #3b82f6;
}

.content-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(350px, 1fr));
  gap: 24px;
}

.content-card {
  height: fit-content;
}

.talk-item {
  padding: 16px 0;
  border-bottom: 1px solid #f0f0f0;
}

.talk-item:last-child {
  border-bottom: none;
}

.talk-header {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 12px;
}

.talk-info {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.talk-content {
  line-height: 1.6;
  margin-bottom: 12px;
}

.talk-tags {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}

.article-item {
  padding: 16px 0;
  border-bottom: 1px solid #f0f0f0;
}

.article-item:last-child {
  border-bottom: none;
}

.article-title {
  display: block;
  margin-bottom: 8px;
  font-size: 16px;
}

.article-desc {
  display: block;
  margin-bottom: 8px;
  line-height: 1.5;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

.article-meta {
  display: flex;
  gap: 16px;
}

.album-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(120px, 1fr));
  gap: 16px;
}

.album-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8px;
}

.album-title {
  font-size: 14px;
  text-align: center;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  width: 100%;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .content-grid {
    grid-template-columns: 1fr;
  }

  .blog-info {
    flex-direction: column;
    text-align: center;
  }

  .album-grid {
    grid-template-columns: repeat(auto-fill, minmax(100px, 1fr));
  }
}
</style>
